# -*- coding: utf-8 -*-
from django.shortcuts import render

from .models import Scripts
from .models import Scripts_Log
from .models import Doinfo
from blueapps.utils.logger import logger

from django.http import JsonResponse
# from django.views.decorators.csrf import csrf_exempt

# from blueking.component.shortcuts import request
from blueking.component.shortcuts import get_client_by_request
from blueking.component.shortcuts import get_client_by_user

from datetime import datetime

from django.template.loader import render_to_string

from django.core.paginator import Paginator

from .celery_tasks import async_status

import logging
import requests,json
import base64

# client = get_client_by_user("105183730")
# client = get_client_by_request(request)
bk_token = "EQ8mYpVvBbYGnWQaUhstMCnjgmb8N_7bO2_6Rt7rYwM"


# 开发框架中通过中间件默认是需要登录态的，如有不需要登录的，可添加装饰器login_exempt
# 装饰器引入 from blueapps.account.decorators import login_exempt
def home(request):
    """
    首页
    """
    return render(request, 'home_application/index_home.html')


def dev_guide(request):
    """
    开发指引
    """
    return render(request, 'home_application/dev_guide.html')


def contact(request):
    """
    联系页
    """
    return render(request, 'home_application/contact.html')


def helloworld(request):
    """
    helloworld
    """
    return render(request, 'home_application/helloworld.html')


def task(request):
    """
    执行任务页
    """
    scripts = Scripts.objects.all()

    # 获取bk_token https://bk.tencent.com/docs/document/5.1/19/610
    # 默认从django settings中获取APP认证信息：应用ID和安全密钥
    # 默认从django request中获取用户登录态bk_token
    # 上线后不提示 下面这个方法会提示{'message': 'Signature [bk_signature] and APP Secret [bk_app_secret] cannot be empty at the same time', 'code': 1306000, 'data': None, 'result': False, 'request_id': '4de1650de97241b89016e3d1273923ee'}
    # client = get_client_by_request(request)
    # r = client.cc.search_business(data)

    # import pdb
    # pdb.set_trace() #运行到这里会自动暂停

    data = {
        "bk_app_code": "bk-xuexi",
        "bk_app_secret": "93229e69-76fb-44b8-ac28-09ec65817ed0",
        "bk_username": "105183730",
        # "bk_token":bk_token,
        "fields": [
            "bk_biz_id",
            "bk_biz_name"
        ],
        "condition": {
            "bk_biz_name": ""
        },
        "page": {
            "start": 0,
            "limit": 10,
            "sort": ""
        }
    }

    # 原始方法必须获得bk_token
    r = requests.post("https://paas-class.bktencent.com/api/c/compapi/v2/cc/search_business/", data=json.dumps(data),
                      verify=False)

    # r = client.cc.search_business(data)
    # print(r)
    rr = json.loads(r.text)
    data = rr['data']
    # info = a['info']

    return render(request, 'home_application/task.html', {"scripts": scripts, "data": data})


# @csrf_exempt
def search_hosts(request):
    data = {
        "bk_app_code": "bk-xuexi",
        "bk_app_secret": "93229e69-76fb-44b8-ac28-09ec65817ed0",
        # "bk_token":bk_token,
        "bk_username": '105183730',
        "bk_biz_id": request.POST.get("bk_biz_id"),
    }
    # print(data['bk_token'])
    r = requests.post("https://paas-class.bktencent.com/api/c/compapi/v2/cc/search_host/", data=data, verify=False)
    rr = json.loads(r.text)

    # a = rr['data']
    # info = a['info']
    # print(info)

    return JsonResponse(rr)


def fast_execute_script1(request):
    bk_biz_id = request.POST.get("bk_biz_id")
    # 拼接ip列表
    temp_ip_list = request.POST.get("host_ips")
    char_string = temp_ip_list.split('\"')
    temp_ip_list_a = []
    ip_dict = {}
    ip_list = []
    for i, x in enumerate(char_string):
        if i % 2 != 0:
            temp_ip_list_a.append(x)
        else:
            continue
    # for i, y in enumerate(temp_ip_list_a):
    #     ip_dict[i]={"bk_cloud_id": 0,"ip":y}
    #     z = ip_dict[i]
    #     ip_list.append(z)
    for y in temp_ip_list_a:
        ip_list.append({"bk_cloud_id": 0, "ip": y})

    print(ip_list)

    # 查找脚本内容
    script_id = request.POST.get("script_id")
    orm = Scripts.objects.get(id=script_id)
    # Python3 base64编码
    script64 = base64.b64encode(orm.text.encode('utf-8'))
    # print(script64)

    data = {
        "bk_app_code": "bk-xuexi",
        "bk_app_secret": "93229e69-76fb-44b8-ac28-09ec65817ed0",
        "bk_username": '105183730',
        "bk_biz_id": bk_biz_id,
        "script_content": str(script64, 'utf-8'),
        "account": "root",
        "script_type": 1,
        "ip_list": ip_list
    }
    r = requests.post("https://paas-class.bktencent.com/api/c/compapi/v2/job/fast_execute_script/", json.dumps(data),
                      verify=False)
    rr = json.loads(r.text)
    # a = rr['data']
    # info = a['info']

    # client = get_client_by_user("105183730")
    # rr = client.job.fast_execute_script(data)

    print(rr)
    # if rr.get('result', False):
    #     data = rr['data']
    #     result = True
    #     message = str(rr.get('message'))
    # else:
    #     data = []
    #     result = False
    #     message = "False!"
    #     logger.error('执行命令失败: s%' % rr.get('message'))

    # 存储执行结果
    # 业务名称

    ex_bk_biz_name = "测试业务"
    print("ex_bk_biz_name:" + ex_bk_biz_name)
    # 用户名 get_job_instance_status/内的operator
    # ex_user = 
    # 任务名称 也就是脚本名称
    ex_script_name = orm.name
    # 操作时间 get_job_instance_status/内的create_time
    # ex_time = 
    # 机器数取执行前ip数量
    ex_ip_count = len(ip_list)
    # 执行状态 get_job_instance_status/内的status
    # ex_status = 
    # 详情按钮后续跳get_job_instance_log

    # 结果保存到数据库
    if (rr['result']):
        save_job_instance_status(rr['data']['job_instance_id'], bk_biz_id, ex_bk_biz_name, ex_script_name, ex_ip_count)

    return JsonResponse(rr)
    # return JsonResponse({"result":result,"message":message,"data":data})


def save_job_instance_status(ex_job_instance_id, ex_bk_biz_id, ex_bk_biz_name, ex_script_name, ex_ip_count):
    ex_job_instance_id = ex_job_instance_id
    ex_bk_biz_name = ex_bk_biz_name
    ex_script_name = ex_script_name
    ex_ip_count = ex_ip_count

    data = {
        "bk_app_code": "bk-xuexi",
        "bk_app_secret": "93229e69-76fb-44b8-ac28-09ec65817ed0",
        "bk_username": '105183730',
        "bk_biz_id": ex_bk_biz_id,
        "job_instance_id": ex_job_instance_id
    }
    r = requests.post("https://paas-class.bktencent.com/api/c/compapi/v2/job/get_job_instance_status/",
                      json.dumps(data), verify=False)
    rr = json.loads(r.text)
    ex_user = rr['data']['job_instance']['operator']
    ex_time = rr['data']['job_instance']['create_time']
    # 作业状态码: 3.执行成功; 4.执行失败;
    ex_status = rr['data']['job_instance']['status']

    scripts_log = Scripts_Log()
    scripts_log.ex_job_instance_id = ex_job_instance_id
    scripts_log.ex_bk_biz_name = ex_bk_biz_name
    scripts_log.ex_user = ex_user
    scripts_log.ex_script_name = ex_script_name
    # 暂时先用自增时间
    # dt = datetime.strptime(ex_time, "%Y-%m-%d %H:%M:%S")
    # scripts_log.ex_time = dt.strftime()

    scripts_log.ex_ip_count = ex_ip_count
    # 作业状态码: 2.正在执行 3.执行成功; 4.执行失败;
    print("ex_status: " + str(ex_status))
    if (ex_status == 3 or ex_status == 2):
        scripts_log.ex_status = "执行成功"
    else:
        scripts_log.ex_status = "执行失败"

    scripts_log.save()

    return


# 查询所有用户信息
def get_usernames(request):
    client = get_client_by_request(request)
    res = client.bk_login.get_all_users()
    usernames = []
    if res.get('result', False):
        for i in res['data']:
            usernames.append(i['bk_username'])
    else:
        logger.error(u'查询所有用户列表失败: %s' % res.get('message'))
    return usernames


def get_biz_info():
    biz_name = []
    biz_id = []
    info = {}
    data = {
        "bk_app_code": "bk-xuexi",
        "bk_app_secret": "93229e69-76fb-44b8-ac28-09ec65817ed0",
        "bk_username": "105183730",
        "fields": [
            "bk_biz_id",
            "bk_biz_name"
        ],
        "condition": {
            "bk_biz_name": ""
        },
    }

    r = requests.post("https://paas-class.bktencent.com/api/c/compapi/v2/cc/search_business/", data=json.dumps(data),
                      verify=False)
    rr = json.loads(r.text)
    if (rr.get('result', False)):
        for i in rr['data']['info']:
            biz_name.append(i['bk_biz_name'])
            biz_id.append(i['bk_biz_id'])
            info = dict(zip(biz_name, biz_id))
    else:
        logger.error(u'请求业务列表失败: %s' % rr.get('message'))
        info = {}

    return info


def task_log(request):
    tasks = Scripts.objects.all()
    doinfos = Doinfo.objects.all()
    data = {
        "info": get_biz_info().items(),
        "usernames": get_usernames(request),
        "tasks": tasks,
        "doinfos": doinfos
    }
    return render(request, 'home_application/task_log.html', data)


# def task_log(request):
#     """
#     任务记录页
#     """
#     scripts_log = Scripts_Log.objects.all()
#     # 业务名称 用户 脚本名称 排重
#     ex_bk_biz_name = Scripts_Log.objects.values('ex_bk_biz_name').order_by('ex_bk_biz_name').distinct()
#     ex_user = Scripts_Log.objects.values('ex_user').order_by('ex_user').distinct()
#     ex_script_name = Scripts_Log.objects.values('ex_script_name').order_by('ex_script_name').distinct()

#     data = {
#         "ex_bk_biz_name":ex_bk_biz_name,
#         "ex_user":ex_user,
#         "ex_script_name":ex_script_name
#     }

#     return render(request, 'home_application/task_log.html', {"data": data})

def search_log(request):
    ex_bk_biz_name = request.POST.get("ex_bk_biz_name")
    ex_user = request.POST.get("ex_user")
    ex_script_name = request.POST.get("ex_script_name")
    # 时间需要转换或模糊查询？
    ex_time = request.POST.get("ex_time")

    # time = "2020/03/27 - 2020/03/31"

    starttime, endtime = ex_time.split('-')
    start_time = starttime.strip().replace('/', '-') + ' 00:00:00'
    starttimes = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
    end_time = endtime.strip().replace('/', '-') + ' 23:59:59'
    endtimes = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')

    print(start_time)
    print(end_time)
    # print(type(start_time))
    # print(type(starttimes))

    orm = Scripts_Log.objects.filter(ex_bk_biz_name=ex_bk_biz_name, ex_user=ex_user, ex_script_name=ex_script_name,
                                     ex_time__range=(starttimes, endtimes)).order_by('ex_job_instance_id')
    records_per_page = 3
    p = Paginator(orm, records_per_page)
    page = request.POST.get("page")
    orm = p.get_page(page)

    # 查询结果需要分页
    print(orm)
    # rr = json.loads(orm)
    tabel_data = render_to_string('home_application/task_log_tbody.html', {'data': orm})
    nav_page = render_to_string('home_application/nav_page.html',
                                {'p': orm, 'page_range': p.page_range, 'page': int(page)})

    return JsonResponse({"result": True, "message": "success", "data": tabel_data, 'nav_page': nav_page})


def search_log2(request):
    try:
        biz_id = request.POST.get('biz_id')
        username = request.POST.get('username')
        script_id = request.POST.get('script_id')
        time = request.POST.get('time')
        doinfo = Doinfo.objects.all()
        doinfo = doinfo.filter(businessname=int(biz_id)).filter(username=username).filter(script_id=int(script_id))
        starttime, endtime = time.split('-')
        starttime = starttime.strip().replace('/','-')+' 00:00:00'
        endtime = endtime.strip().replace('/','-')+' 23:59:00'
        start_time = datetime.strptime(starttime,'%Y-%m-%d %H:%M:%S')
        end_time = datetime.strptime(endtime,'%Y-%m-%d %H:%M:%S')
        orm = doinfo.filter(starttime__range=(start_time,end_time))
        # data = [info.to_dict() for info in orm]
        # print("biz_id "+biz_id)
        # print("username "+ str(username))
        # print("script_id "+script_id)
        # print(data)
        records_per_page = 3
        p = Paginator(orm, records_per_page)
        page = request.POST.get("page")
        orm = p.get_page(page)
        # 查询结果需要分页
        print(orm)
        # rr = json.loads(orm)
        tabel_data = render_to_string('home_application/task_log_tbody.html', {'data': orm})
        nav_page = render_to_string('home_application/nav_page.html',
                                    {'p': orm, 'page_range': p.page_range, 'page': int(page)})
        result = True
        message = "success"
    except Exception as err:
        data = []
        result = False
        message = str(err)
    # return  JsonResponse({"result": result,"message":message,"data":data})
    return JsonResponse({"result": True, "message": "success", "data": tabel_data, 'nav_page': nav_page})


# 执行任务
def fast_execute_script(request):
    client = get_client_by_request(request)
    bk_biz_id = request.POST.get("bk_biz_id")
    # 拼接ip列表
    temp_ip_list = request.POST.get("host_ips")
    char_string = temp_ip_list.split('\"')
    temp_ip_list_a = []
    ip_dict = {}
    ip_list = []
    for i, x in enumerate(char_string):
        if i % 2 != 0:
            temp_ip_list_a.append(x)
        else:
            continue
    # for i, y in enumerate(temp_ip_list_a):
    #     ip_dict[i]={"bk_cloud_id": 0,"ip":y}
    #     z = ip_dict[i]
    #     ip_list.append(z)
    for y in temp_ip_list_a:
        ip_list.append({"bk_cloud_id": 0, "ip": y})

    print(ip_list)

    # 查找脚本内容
    script_id = request.POST.get("script_id")
    orm = Scripts.objects.get(id=script_id)
    # Python3 base64编码
    script64 = base64.b64encode(orm.text.encode('utf-8'))
    # print(script64)

    data = {
        "bk_app_code": "bk-xuexi",
        "bk_app_secret": "93229e69-76fb-44b8-ac28-09ec65817ed0",
        "bk_username": '105183730',
        "bk_biz_id": bk_biz_id,
        "script_content": str(script64, 'utf-8'),
        "account": "root",
        "script_type": 1,
        "ip_list": ip_list
    }
    r = requests.post("https://paas-class.bktencent.com/api/c/compapi/v2/job/fast_execute_script/", json.dumps(data),
                      verify=False)
    rr = json.loads(r.text)

    print(rr)

    if rr.get('result', False):
        data2 = rr['data']
        result = True
        message = str(rr.get('message'))
        print("脚本在服务端执行成功！")
        # 异步查询执行结果
        async_status.apply_async(args=[client, data2, bk_biz_id, orm, ip_list], kwargs={})
        # async_status.apply_async(args=[ip_list],kwargs={})
    else:
        data = []
        result = False
        message = "False"
        logger.error(u'查询执行日志失败: %s' % rr.get('message'))
    return JsonResponse({"result": result, "message": message, "data": data2})


def ar_data1(request):
    data_type = request.POST.get("data_type")

    if (data_type == "barChart"):
        data = {
            "tpye": "barChart",
            "1": '10',
            "2": '20',
            "3": '30',
        }
    else:
        data = {}

    result = True

    return JsonResponse({"result": result, "data": json.dumps(data)})
